// NutritionViewModel.kt
package com.example.nutritionmanager.viewModels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.nutritionmanager.api.NutritionService
import com.example.nutritionmanager.bodys.requestBodys.Record
import com.example.nutritionmanager.bodys.requestBodys.RecordItem
import com.example.nutritionmanager.bodys.responseBodys.Nutrition
import com.example.nutritionmanager.bodys.responseBodys.NutritionAmount
import com.example.nutritionmanager.event.EventBus
import com.example.nutritionmanager.event.IntakeRefreshEvent
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject

// 定义营养状态的密封类（保留原有状态，并添加新的营养量状态）
sealed class NutritionState {
    object Idle : NutritionState() // 初始状态
    object Loading : NutritionState() // 加载中
    data class Success(val nutritions: List<Nutrition>) : NutritionState() // 成功获取营养数据
    data class Error(val error: String) : NutritionState() // 获取营养数据时发生错误
    data class SaveSuccess(val message: String) : NutritionState() // 保存成功
    data class SaveError(val error: String) : NutritionState() // 保存时发生错误
}

sealed class NutritionAmountState {
    object Idle : NutritionAmountState()
    object Loading : NutritionAmountState()
    data class Success(val date: String, val amounts: List<NutritionAmount>) : NutritionAmountState()
    data class Error(val date: String, val error: String) : NutritionAmountState()
}
@HiltViewModel
class NutritionViewModel @Inject constructor(
    private val nutritionService: NutritionService
) : ViewModel() {

    // 状态流：获取所有营养成分
    private val _nutritionState = MutableStateFlow<NutritionState>(NutritionState.Idle)
    val nutritionState: StateFlow<NutritionState> = _nutritionState.asStateFlow()

    // 状态流：获取特定日期的营养摄入量
    private val _nutritionAmountState = MutableStateFlow<NutritionAmountState>(NutritionAmountState.Idle)
    val nutritionAmountState: StateFlow<NutritionAmountState> = _nutritionAmountState.asStateFlow()

    val nutritionList = listOf(Nutrition(1, "热量", "", "kcal"), Nutrition(2, "蛋白质", "", "g"), Nutrition(3, "脂肪", "", "g"), Nutrition(4, "碳水化合物", "", "g"))
    // 选中的营养成分列表
    private val _selectedNutritions = MutableStateFlow<List<Nutrition>>(nutritionList)
    val selectedNutritions: StateFlow<List<Nutrition>> = _selectedNutritions.asStateFlow()

    // 每个营养成分的输入值
    private val _nutritionInputs = MutableStateFlow<Map<Int, String>>(emptyMap())
    val nutritionInputs: StateFlow<Map<Int, String>> = _nutritionInputs.asStateFlow()

    init {
        initNutritionList()
        fetchAllNutritions()
    }

    private fun initNutritionList() {
        _selectedNutritions.value = nutritionList
        _nutritionInputs.value = nutritionList.associate { it.nutritionId to "" }
    }

    // 获取所有营养成分的方法
    private fun fetchAllNutritions() {
        viewModelScope.launch {
            _nutritionState.value = NutritionState.Loading
            try {
                val response = nutritionService.getAllNutritions()
                if (response.isSuccessful) {
                    val nutritions = response.body() ?: emptyList()
                    _nutritionState.value = NutritionState.Success(nutritions)
                } else {
                    _nutritionState.value = NutritionState.Error("加载营养成分失败")
                }
            } catch (e: Exception) {
                _nutritionState.value = NutritionState.Error(e.localizedMessage ?: "发生错误")
            }
        }
    }

    // 添加一个营养成分到选中的列表中
    fun addNutrition(nutrition: Nutrition) {
        if (!_selectedNutritions.value.contains(nutrition)) {
            _selectedNutritions.value = _selectedNutritions.value + nutrition
            _nutritionInputs.value = _nutritionInputs.value + (nutrition.nutritionId to "")
        }
    }

    // 从选中的列表中移除一个营养成分
    fun removeNutrition(nutrition: Nutrition) {
        _selectedNutritions.value = _selectedNutritions.value - nutrition
        _nutritionInputs.value = _nutritionInputs.value - nutrition.nutritionId
    }

    // 更新某个营养成分的输入值
    fun updateNutritionInput(nutritionId: Int, value: String) {
        _nutritionInputs.value = _nutritionInputs.value + (nutritionId to value)
    }

    // 获取特定日期的营养摄入量
    fun fetchNutritionAmountByDate(date: String) {
        viewModelScope.launch {
            _nutritionAmountState.value = NutritionAmountState.Loading
            try {
                val response = nutritionService.getNutritionAmountByDate(date)
                if (response.isSuccessful) {
                    val amounts = response.body() ?: emptyList()
                    _nutritionAmountState.value = NutritionAmountState.Success(date, amounts)
                } else {
                    _nutritionAmountState.value = NutritionAmountState.Error(date, "加载营养摄入量失败")
                }
            } catch (e: Exception) {
                _nutritionAmountState.value = NutritionAmountState.Error(date, e.localizedMessage ?: "发生错误")
            }
        }
    }

    // 保存营养记录的方法（根据您的需求实现）
    fun saveNutritionRecord(date: String, mealType: Int) {
        viewModelScope.launch {
            _nutritionState.value = NutritionState.Loading
            try {
                // 1. 验证输入有效性
                val validationResult = validateInputs()
                if (!validationResult.isValid) {
                    _nutritionState.value = NutritionState.SaveError(validationResult.errorMessage)
                    return@launch
                }
                // 2. 构建请求体
                val record = buildRecord(date, mealType)
                // 3. 调用API
                val response = nutritionService.addNutritionRecord(record)

                if (response.isSuccessful) {
                    _nutritionState.value = NutritionState.SaveSuccess("记录保存成功")
                    initNutritionList() // 保存成功后重置营养列表
                    EventBus.post(IntakeRefreshEvent.RefreshData)


                } else {
                    val errorBody = response.errorBody()?.string() ?: "未知错误"
                    _nutritionState.value = NutritionState.SaveError("保存失败: $errorBody")
                }
            } catch (e: Exception) {
                _nutritionState.value = NutritionState.SaveError("网络错误: ${e.localizedMessage}")
            }
        }
    }

    // 重置状态的方法
    fun resetState() {
        _nutritionState.value = NutritionState.Idle
        _nutritionAmountState.value = NutritionAmountState.Idle
    }

    // 输入验证
    private fun validateInputs(): ValidationResult {
        val invalidItems = selectedNutritions.value.filter { nutrition ->
            val value = nutritionInputs.value[nutrition.nutritionId]
            value.isNullOrBlank() || value.toDoubleOrNull() == null
        }

        return if (invalidItems.isNotEmpty()) {
            val names = invalidItems.joinToString { it.nutritionName }
            ValidationResult(false, "以下数值无效: $names")
        } else {
            ValidationResult(true)
        }
    }

    // 构建请求体
    private fun buildRecord(date: String, mealType: Int): Record {
        return Record(
            date = date,
            mealType = mealType,
            nutrients = selectedNutritions.value.map { nutrition ->
                RecordItem(
                    nutritionId = nutrition.nutritionId,
                    nutritionName = nutrition.nutritionName,
                    amount = nutritionInputs.value[nutrition.nutritionId]?.toDouble() ?: 0.0
                )
            }
        )
    }

    // 验证结果数据类
    private data class ValidationResult(
        val isValid: Boolean,
        val errorMessage: String = ""
    )
}
